package cn.xuqiudong.blog.module.third.service;

import cn.xuqiudong.common.base.exception.CommonException;
import cn.xuqiudong.common.blog.model.BlogThirdUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述: 第三方授权处理
 * @author Vic.xu
 * @since 2022-08-10 17:46
 */
@Service
public class OauthFacade {

    @Autowired
    private Collection<AbstractAuthService> authServices;

    private Map<String, AbstractAuthService> abstractAuthServiceMap;

    @PostConstruct
    private void initAbstractAuthServiceMap() {
        abstractAuthServiceMap = new HashMap<>();
        if (authServices != null) {
            for (AbstractAuthService authService : authServices) {
                abstractAuthServiceMap.put(authService.type().name(), authService);
            }
        }
    }

    /**
     * 根据授权码code 获取用户信息，并更新本地数据库
     * @param type 授权类型 {@link cn.xuqiudong.blog.constant.GlobalFieldParams.ThirdTypeEnum}
     * @param code  第三方授权码
     * @return BlogThirdUser
     */
    public BlogThirdUser findUserInfoByCode(String type, String code) {
        AbstractAuthService abstractAuthService = abstractAuthServiceMap.get(type);
        if (abstractAuthService == null) {
            throw new CommonException("不存在的授权方式");
        }
        return abstractAuthService.findUserInfoByCode(code);
    }

}
